package cn.com.callback

import cn.com.kh.KHUtil
import com.alibaba.fastjson.JSONArray
import com.alibaba.fastjson.JSONObject
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.com.callback.ServiceBackInvoke
import cn.com.elite.EliteBean;
import cn.com.elite.Util;
import java.text.SimpleDateFormat;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import cn.com.kh.getProperty;
/**
 *
 * @Title: aipHSTsubBankCard
 * @Description:华盛证券 将各渠道填写的申请子账户任务/审核结果 实时推送至CRM系统 --外部接口
 * @author: chieh
 * @date 2022-09-20 10:28:00
 *
 */

public class aipHSTsubBankCard implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(aipHSTsubBankCard.class);
    String custapiid = getProperty.get("custapiid");
    String custapikey = getProperty.get("custapikey");
    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {
        response.setCharacterEncoding("UTF-8");

        String getMethod = request.getMethod();

        log.debug("getMethod:" + getMethod);
        long endTime ;
        String inData = "";
        String outData = "";
        String dataSourceID = "dataSource";

        BufferedReader iny = null;
        if (getMethod.equals("GET")) {
            inData = request.getParameter("data");
            log.debug("原始Get请求参数:" + inData);
        } else {
            InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
            iny = new BufferedReader(reader);
            String line;
            while ((line = iny.readLine()) != null) {
                inData += line;
            }
            log.debug("原始Post请求参数:" + inData);
        }

        try {
            long startTime = System.currentTimeMillis();

            // 调用处理信息
            JSONObject inObject = JSONObject.parseObject(inData);
            log.debug("处理前的Json：" + inObject.toString());
            def apiid = inObject.getString("apiid");
            if(custapiid!=apiid){

                return "{\"resultcode\":\"0\",\"resultmessage\":\"处理失败(apiid不匹配),调用问题处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":[]}";
            }
            def timestamp = inObject.getString("timestamp");
            def sign = inObject.getString("sign");
            def apitype = inObject.getString("apitype");
            log.debug("解析信息-" + "apiid: " + apiid + "timestamp: " + timestamp + "	sign: " + sign + "	apitype: " + apitype);

            //  String apikey = "c5e5e59567162a6be0533228d50a17e9";
            String signfront = "apiid" + "=" + apiid + "&" + "apikey" + "=" + custapikey + "&" + "timestamp" + "=" + timestamp;
            log.debug("sign加密MD5前：" + signfront);

            String signafter = Util.getMD5Str(signfront);
            log.debug("sign加密MD5后：" + signafter);

            if (!signafter.equals(sign)) {
                log.error("处理失败(sign签名错误)!");
                endTime = System.currentTimeMillis();
                return "{\"resultcode\":\"0\",\"resultmessage\":\"处理失败(sign签名错误),调用问题处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":[]}";
            }
            //传 apply  属申请任务同步
            if(apitype=="apply"){
                outData = applyData(eliteBean, inObject, dataSourceID);
            }else if(apitype=="result"){// result 则按审核结果更新
                outData = resultData(eliteBean, inObject, dataSourceID);
            }

        } catch (Exception e) {
            log.error("接口处理异常" + e.getMessage());
            outData = "{\"resultcode\":\"0\",\"resultmessage\":\"处理失败(" + e.getMessage() + ")\",\"data\":[]}";
        }

        log.debug("开户(入金)客户信息完成返回结果:" + outData);

        return outData;
    }

    // 处理申请任务
    public static String applyData(EliteBean eliteBean, JSONObject inObject, String dataSourceID) {

        long startTime = System.currentTimeMillis();
        long endTime = System.currentTimeMillis();

        SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String createdate = dateformat.format(System.currentTimeMillis());

        // 生成批次号
        String batch_guid = KHUtil.getRandomString(36).toUpperCase();

        // 定义返回对象
        JSONObject resultJson = new JSONObject();

        try {

            JSONArray arrJsonArray = inObject.getJSONArray("data");
            int arrInt = arrJsonArray.size();
            log.debug("接入List数量:" + arrInt);

            String[] insertSQL = new String[arrInt];

            for (int i = 0; i < arrInt; i++) {

                JSONObject arrSmsJson = arrJsonArray.getJSONObject(i);

                String sourceId = KHUtil.FastJsonNull(arrSmsJson.getString("sourceId"));//来源渠道 1 APP 2 其他
                String customerId = KHUtil.FastJsonNull(arrSmsJson.getString("customerId"));//华盛号
                String applyTime = KHUtil.FastJsonNull(arrSmsJson.getString("applyTime"));//申请时间
                String accountStatus = KHUtil.FastJsonNull(arrSmsJson.getString("accountStatus"));//账户状态

                String deal_result = KHUtil.isNullMSG("sourceId", sourceId)  + KHUtil.isNullMSG("customerId", customerId) + KHUtil.isNullMSG("applyTime", applyTime);
                int deal_flag = KHUtil.isNull(deal_result) ? 0 : -1;

                def getobjcustSelectSQL = eliteBean.chaxun_sql("Select o.HANDLEBY_ID as HANDLEBY_ID,o.Customer_Guid as Customer_Guid,o.objective_guid as objective_guid,c.mobile,c.CUSTOMERNAME,c.STRINGFIELD17 From Customer c left join objective o  on c.customer_guid=o.customer_guid Where 1=1  and c.Customer_Id = '" + customerId + "' and o. Map_Id='MY48ZX'", "dataSource");
                def HANDLEBY_ID,Customer_Guid,objective_guid,mobile,CUSTOMERNAME,STRINGFIELD17="";
                if (getobjcustSelectSQL.size() > 0) {
                    HANDLEBY_ID = getobjcustSelectSQL.get(i).get("HANDLEBY_ID");
                    Customer_Guid = getobjcustSelectSQL.get(i).get("Customer_Guid");
                    objective_guid = getobjcustSelectSQL.get(i).get("objective_guid");
                    mobile = getobjcustSelectSQL.get(i).get("mobile");
                    CUSTOMERNAME = getobjcustSelectSQL.get(i).get("CUSTOMERNAME");
                    STRINGFIELD17 = getobjcustSelectSQL.get(i).get("STRINGFIELD17");

                }else{
                    HANDLEBY_ID="";
                    Customer_Guid="";
                    objective_guid="";
                    mobile="";
                    CUSTOMERNAME="";
                    STRINGFIELD17="";
                }
				if(HANDLEBY_ID==null){
                    HANDLEBY_ID="";
                }
                if(Customer_Guid==null){
                    Customer_Guid="";
                }
                if(objective_guid==null){
                    objective_guid="";
                }
                if(mobile==null){
                    mobile="";
                }
                if(CUSTOMERNAME==null){
                    CUSTOMERNAME="";
                }
                if(STRINGFIELD17==null){
                    STRINGFIELD17="";
                }

                insertSQL[i] = "INSERT INTO hst_examine (id,typeid,hstid , name ,objective_guid, phone ,state, content,Createdby,Createddate,synctime,sourceChannel,accountStatus,CUSTOMERNAME,STRINGFIELD17)  VALUES (uuid(),'004','" + customerId + "', '" + Customer_Guid + "', '" + objective_guid+ "', '" + mobile + "','0', '华盛接口同步申请', '" + HANDLEBY_ID + "', '" + applyTime + "', '" + createdate + "', '" + sourceId + "', '" + accountStatus + "', '" + CUSTOMERNAME + "', '" + STRINGFIELD17 + "')";

            }

            // 处理批次信息
            String enddate = dateformat.format(System.currentTimeMillis());
            log.debug("提交数据库操作SQL集:" + insertSQL.toString());

            // 将数据插入数据库
            int[] sqlResult = eliteBean.updateBatch(insertSQL, dataSourceID);
            log.debug("提交数据库操作SQL结果:" + sqlResult.toString());

            // 生成处理完成时间
            endTime = System.currentTimeMillis();

            // 包装拼接返回JSONObject
            resultJson.put("resultcode", 1);
            resultJson.put("resultmessage", "处理完成,调用问题处理时长(毫秒):" + (endTime - startTime));
        } catch (Exception e) {
            endTime = System.currentTimeMillis();
            resultJson.put("resultcode", 4);
            resultJson.put("resultmessage", "处理失败:(" + e.getMessage() + ")" + "处理完成,调用问题处理时长(毫秒):" +(endTime -startTime));

        }

        return resultJson.toString();
    }

    // 处理审核结果任务
    public static String resultData(EliteBean eliteBean, JSONObject inObject, String dataSourceID) {

        long startTime = System.currentTimeMillis();
        long endTime = System.currentTimeMillis();

        SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String createdate = dateformat.format(System.currentTimeMillis());

        // 生成批次号
        String batch_guid = KHUtil.getRandomString(36).toUpperCase();

        // 定义返回对象
        JSONObject resultJson = new JSONObject();

        try {

            JSONArray arrJsonArray = inObject.getJSONArray("data");
            int arrInt = arrJsonArray.size();
            log.debug("接入List数量:" + arrInt);

            String[] insertSQL = new String[arrInt*2];

            for (int i = 0; i < arrInt; i++) {

                JSONObject arrSmsJson = arrJsonArray.getJSONObject(i);

                String bankCardId = KHUtil.FastJsonNull(arrSmsJson.getString("bankCardId"));//主账号ID
                String customerId = KHUtil.FastJsonNull(arrSmsJson.getString("customerId"));//华盛号
                String status = KHUtil.FastJsonNull(arrSmsJson.getString("status"));//审核状态  1 已开通 2 已驳回 3 已回收
                String rejectcontent = KHUtil.FastJsonNull(arrSmsJson.getString("rejectcontent"));//驳回原因
                String subBankCardNo = KHUtil.FastJsonNull(arrSmsJson.getString("subBankCardNo"));//子账户号码
                String subBankCardName = KHUtil.FastJsonNull(arrSmsJson.getString("subBankCardName"));//子账户名称前缀

                String deal_result = KHUtil.isNullMSG("bankCardId", bankCardId)  + KHUtil.isNullMSG("customerId", customerId) + KHUtil.isNullMSG("status",status) ;
                int deal_flag = KHUtil.isNull(deal_result) ? 0 : -1;

                //落库更新
                insertSQL[i*2] = "update  hst_examine c  set c.auditStatus='" + status+ "',c.auditContent='" + rejectcontent+ "',c.subBankCardNo='" + subBankCardNo+ "',c.subBankCardName='" + subBankCardName+ "',c.resultsynctime='" + createdate+ "'  where c.hstid='"+customerId+"' and c.bankCardId='"+bankCardId+"' and IFNULL(c.auditStatus,'')!='3'  and typeid='004'";
                //详情表记录
                insertSQL[i*2+1] = "insert into hst_subBankCard(bankCardId,customerid,status,rejectcontent,subBankCardNo,subBankCardName,createdate,deal_flag,deal_result) VALUES('"+bankCardId+"','"+customerId+"','"+status+"','"+rejectcontent+"','"+subBankCardNo+"','"+subBankCardName+"',now(),'"+deal_flag+"','"+deal_result+"')";

            }

            // 处理批次信息
            String enddate = dateformat.format(System.currentTimeMillis());
            log.debug("提交数据库操作SQL集:" + insertSQL.toString());

            // 将数据插入数据库
            int[] sqlResult = eliteBean.updateBatch(insertSQL, dataSourceID);
            log.debug("提交数据库操作SQL结果:" + sqlResult.toString());

            // 生成处理完成时间
            endTime = System.currentTimeMillis();

            // 包装拼接返回JSONObject
            resultJson.put("resultcode", 1);
            resultJson.put("resultmessage", "处理完成,调用问题处理时长(毫秒):" + (endTime - startTime));
        } catch (Exception e) {
            endTime = System.currentTimeMillis();
            resultJson.put("resultcode", 4);
            resultJson.put("resultmessage", "处理失败:(" + e.getMessage() + ")" + "处理完成,调用问题处理时长(毫秒):" +(endTime -startTime));

        }

        return resultJson.toString();
    }

}
